package com.vicene.gmail.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.vicene.gmail.product.service.CategoryBrandRelationService;
import com.vicene.gmail.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vicene.gmail.common.utils.PageUtils;
import com.vicene.gmail.common.utils.Query;

import com.vicene.gmail.product.dao.CategoryDao;
import com.vicene.gmail.product.entity.CategoryEntity;
import com.vicene.gmail.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构

        //2.1）、找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());




        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1,检查当前删除菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);

        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    //删除以category分区的所有缓存
    //@CacheEvict(value = "category" , allEntries = true)
    //多种缓存失效
    @Caching(evict = {
            @CacheEvict(value = "category", key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category", key = "'getCatalogJson'")
    })
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId() , category.getName());

        //缓存一致性失效模式：删除三级分类，查询时重新生成json
        this.stringRedisTemplate.delete("catalogJson");
    }



    //每个需要缓存的数据都来指定要放到哪个名字的缓存【缓存分区（按照业务类型分）】
    //把当前方法的结果缓存，如果有方法不调用，如果没有，调用方法
    //key为category::getLevel1Categorys 参考SPEL，过期时间为3600000ms,
    @Cacheable(value = {"category"} , key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid" , 0) ) ;
    }

    @Cacheable(value = {"category"} , key = "#root.method.name" , sync=true)
    @Override
    public Map< String ,List<Catelog2Vo>>  getCatalogJson() {
//        String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
//        if(StringUtils.isEmpty(catalogJson)){
//            Map< String ,List<Catelog2Vo>>  catalogJsonFromDbB =this.getCatalogJsonFromDbB();
//
//            //增加随机过期时间，解决缓存雪崩
//            stringRedisTemplate.opsForValue().set("catalogJson" , JSON.toJSONString(catalogJsonFromDbB) , 1 , TimeUnit.DAYS);
//            return catalogJsonFromDbB;
//        }
//
//        Map< String ,List<Catelog2Vo>> result = JSON.parseObject(catalogJson ,
//                new TypeReference<Map<String ,List<Catelog2Vo>>>(){});

        Map< String ,List<Catelog2Vo>>  catalogJsonFromDbB =this.getCatalogJsonFromDbB();

        return catalogJsonFromDbB;

    }


    public Map< String ,List<Catelog2Vo>>  getCatalogJsonFromDbB() {
        Map< String ,List<Catelog2Vo>> map = getCatalogJsonFromDbWithRedissonLock();
        //解决缓存穿透问题
//        String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
//        if(!StringUtils.isEmpty(catalogJson)){
//            Map< String ,List<Catelog2Vo>> result = JSON.parseObject(catalogJson ,
//                    new TypeReference<Map<String ,List<Catelog2Vo>>>(){});
//
//            return result;
//        }
//        //TODO 本地锁存在问题，如果分布式部署？
//        RLock lock = redissonClient.getLock("catalogJson");
//        Map< String ,List<Catelog2Vo>> map = null;
//
//        lock.lock();
//        //synchronized (this){
//        try{
//            map = getCatalogJsonFromDbWithRedissonLock();
//            //业务时序问题，需要在放入redis后释放锁，不然会执行多次查询DB
//            stringRedisTemplate.opsForValue().set("catalogJson" ,
//                    JSON.toJSONString(JSON.toJSONString(map)) , 1 , TimeUnit.DAYS);
//
//        }catch(Exception e){
//            e.printStackTrace();
//        }finally {
//            lock.unlock();
//        }
        return map;
    }

    private Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {


        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_cid(selectList , 0L);
        Map< String ,List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(
                k->k.getCatId().toString(),v->{
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList , v.getCatId());
                    List<Catelog2Vo> catelog2VoList = null;
                    if(categoryEntities!=null){
                        catelog2VoList = categoryEntities.stream().map(l2-> {
                            Catelog2Vo catelog2Vo =  new Catelog2Vo(v.getCatId().toString(),null,l2.getCatId().toString() , l2.getName());
                            List<CategoryEntity> level3Catelog = getParent_cid(selectList , l2.getCatId());
                            if(level3Catelog != null){
                                List<Catelog2Vo.Catelog3Vo> collect =  level3Catelog.stream().map(l3 ->{
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(),l3.getCatId().toString() , l3.getName() );
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(collect);
                            }

                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catelog2VoList;
                }));

        return parent_cid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> categoryEntityList , Long parent_cid) {

        return categoryEntityList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());


    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if(categoryEntity.getParentCid() != 0){
            findParentPath(categoryEntity.getParentCid() , paths);
        }
        return paths;
    }


    private List<CategoryEntity> getChildrens(CategoryEntity root , List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //2、菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }


}